<!-- 工序锁定 -->
<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.processLock_add" @click="handleAdd">新增锁定</el-button>
        <el-button type="danger" size="small" icon="el-icon-unlock" v-if="permission.processLock_unLock" @click="handleBatchUnLock">批量解锁</el-button>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-unlock" size="small" type="text" v-if="permission.processLock_unLock" @click="openUnLockDialog(row)" v-preventReClick>解锁</el-button>
        <el-button icon="el-icon-view" size="small" type="text" @click="handleView(row, index)" v-preventReClick>查看</el-button>
      </template>
    </avue-crud>

    <!-- 解除锁定 -->
    <el-dialog
      custom-class="materialUnlockDialog"
      append-to-body
      :close-on-click-modal="false"
      title="解除锁定"
      v-if="unlockDialog.show"
      :visible.sync="unlockDialog.show"
      width="50%"
      top="15vh"
    >
      <avue-form v-if="unLockType == 'batch'" ref="unlockRef" v-model="unlockDialog.form" :option="unlockDialog.batchOption" @submit="handleunLockSubmit">
        <template #selectInfoData>
          <avue-crud :option="unlockData.option" :data="unlockData.data">
            <template slot-scope="{ row, index }" slot="menu">
              <el-button icon="el-icon-delete" size="small" type="text" @click="unlockDelete(row, index)">删除</el-button>
            </template>
          </avue-crud>
        </template>
      </avue-form>
      <avue-form v-if="unLockType == 'single'" ref="unlockRef" v-model="unlockDialog.form" :option="unlockDialog.singleOption" @submit="handleunLockSubmit"> </avue-form>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, partLock, unLock, getRoutesByWo } from '@/api/quality/processLock';
import { mapGetters } from 'vuex';
export default {
  name: 'ProcessLock',
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      unLockType: 'single', // 解锁类型:单个解锁还是批量解锁
      option: {
        height: 'calc(100vh - 380px)',
        calcHeight: 30,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 5,
        border: true,
        index: true,
        selection: true,
        dialogClickModal: false,
        dialogCustomClass: 'materialLockDialog',
        addBtn: false,
        addTitle: '新增锁定',
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        indexLabel: '序号',
        dialogWidth: '50%',
        menuWidth: 150,
        labelWidth: 100,
        column: [
          {
            label: '操作时间',
            prop: 'lockedTimes',
            hide: true,
            searchSpan: 7,
            searchOrder: 1,
            searchType: 'datetimerange',
            search: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            display: false
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            width: 150,
            search: true,
            searchSpan: 4,
            searchOrder: 4,
            overHidden: true,
            display: false
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            width: 150,
            search: true,
            searchSpan: 4,
            searchOrder: 2,
            overHidden: true,
            display: false
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            width: 150,
            overHidden: true,
            display: false
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            search: true,
            searchSpan: 4,
            searchOrder: 3,
            overHidden: true,
            display: false
          },
          {
            label: '锁定维度',
            prop: 'lockDimensionStr',
            overHidden: true,
            display: false
          },
          {
            label: '锁定原因',
            prop: 'lockReason',
            overHidden: true,
            display: false
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            html: true,
            formatter: () => {
              return `<span class="stateWords-danger">锁定</span>`;
            },
            display: false
          },
          {
            label: '操作人',
            prop: 'lockByName',
            display: false
          },
          {
            label: '操作时间',
            prop: 'lockTime',
            width: 130,
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            display: false
          },
          {
            label: '已锁定时间',
            prop: 'lockDuration',
            display: false
          }
        ],
        group: [
          {
            label: '产品信息',
            prop: 'partInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '工单号',
                prop: 'workOrderNo',
                searchType: 'input',
                type: 'search',
                disabled: true,
                order: 1,
                appendClick: () => {
                  this.openWorkOrderModal();
                },
                rules: [
                  {
                    required: true,
                    message: '请选择工单号',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '产品名称',
                prop: 'productPartName',
                disabled: true
              },
              {
                label: '产品编码',
                prop: 'productPartNo',
                disabled: true
              },
              {
                label: '产品型号',
                prop: 'productPartModel',
                disabled: true
              }
            ]
          },
          {
            label: '锁定维度',
            prop: 'lockDimension',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '维度',
                prop: 'lockDimension',
                type: 'radio',
                span: 24,
                value: 'WORKORDER',
                dicData: [
                  {
                    label: '工单',
                    value: 'WORKORDER'
                  },
                  {
                    label: '工序',
                    value: 'ROUTE'
                  }
                ],
                control: (val, form) => {
                  if (val === 'WORKORDER') {
                    return {
                      lockDimensionDetail: {
                        display: false
                      }
                    };
                  } else if (val === 'ROUTE') {
                    return {
                      lockDimensionDetail: {
                        display: true
                      }
                    };
                  }
                }
              },
              {
                label: '工序',
                prop: 'lockDimensionDetail',
                type: 'select',
                multiple: true,
                dicData: [],
                span: 24,
                rules: [
                  {
                    required: true,
                    message: '请选择工序',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          },
          {
            column: [
              {
                label: '锁定原因',
                prop: 'lockReason',
                type: 'textarea',
                row: true,
                span: 24,
                maxRows: 3,
                minRows: 3,
                rules: [
                  {
                    required: true,
                    message: '请输入锁定原因',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          }
        ]
      },
      unlockDialog: {
        show: false,
        rowData: null,
        form: {
          unlockReason: ''
        },
        singleOption: {
          labelWidth: '100',
          submitBtn: true,
          emptyBtn: true,
          menuPosition: 'right',
          group: [
            {
              label: '锁定信息',
              prop: 'selectInfo',
              arrow: false,
              icon: 'el-icon-vertical-bar',
              column: [
                {
                  label: '工单号',
                  prop: 'workOrderNo',
                  disabled: true,
                  span: 12
                },
                {
                  label: '产品名称',
                  prop: 'productPartName',
                  disabled: true,
                  span: 12
                },
                {
                  label: '产品编码',
                  prop: 'productPartNo',
                  disabled: true,
                  span: 12
                },
                {
                  label: '产品型号',
                  prop: 'productPartModel',
                  disabled: true,
                  span: 12
                },
                {
                  label: '锁定维度',
                  prop: 'lockDimension',
                  disabled: true,
                  type: 'select',
                  dicData: [
                    {
                      label: '工单',
                      value: 'WORKORDER'
                    },
                    {
                      label: '工序',
                      value: 'ROUTE'
                    }
                  ],
                  span: 12,
                  control: (val, form) => {
                    if (val === 'WORKORDER') {
                      return {
                        lockDimensionDetail: {
                          display: false
                        }
                      };
                    } else if (val === 'ROUTE') {
                      return {
                        lockDimensionDetail: {
                          display: true
                        }
                      };
                    }
                  }
                },
                {
                  label: '已锁定工序',
                  prop: 'lockDimensionDetail',
                  disabled: true,
                  span: 24
                },
                {
                  label: '锁定原因',
                  prop: 'lockReason',
                  type: 'textarea',
                  disabled: true,
                  row: true,
                  span: 24,
                  maxRows: 3,
                  minRows: 3
                }
              ]
            },
            {
              label: '解除锁定',
              prop: 'lock',
              arrow: false,
              icon: 'el-icon-vertical-bar',
              column: [
                {
                  label: '解锁说明',
                  prop: 'unlockReason',
                  span: 24,
                  type: 'textarea',
                  showWordLimit: true,
                  maxlength: 200,
                  rules: [
                    {
                      required: true,
                      message: '请输入解锁说明',
                      trigger: 'blur'
                    }
                  ]
                }
              ]
            }
          ]
        },
        batchOption: {
          labelWidth: '100',
          submitBtn: true,
          emptyBtn: true,
          menuPosition: 'right',
          group: [
            {
              label: '锁定信息',
              prop: 'selectInfo',
              arrow: false,
              icon: 'el-icon-vertical-bar',
              column: [
                {
                  label: '',
                  labelWidth: 0,
                  prop: 'selectInfoData',
                  span: 24,
                  formslot: true
                }
              ]
            },
            {
              label: '解除锁定',
              prop: 'lock',
              arrow: false,
              icon: 'el-icon-vertical-bar',
              column: [
                {
                  label: '解锁说明',
                  prop: 'unlockReason',
                  span: 24,
                  type: 'textarea',
                  showWordLimit: true,
                  maxlength: 200,
                  rules: [
                    {
                      required: true,
                      message: '请输入解锁说明',
                      trigger: 'blur'
                    }
                  ]
                }
              ]
            }
          ]
        }
      },
      unlockData: {
        option: {
          height: '200px',
          calcHeight: 30,
          searchShow: false,
          border: true,
          index: true,
          selection: false,
          addBtn: false,
          viewBtn: false,
          editBtn: false,
          delBtn: false,
          refreshBtn: false,
          columnBtn: false,
          tip: false,
          indexLabel: '序号',
          menu: true,
          menuWidth: 100,
          column: [
            {
              label: '工单号',
              prop: 'workOrderNo'
            },
            {
              label: '产品编码',
              prop: 'productPartNo'
            },
            {
              label: '产品名称',
              prop: 'productPartName'
            },
            {
              label: '产品型号',
              prop: 'productPartModel'
            },
            {
              label: '锁定维度',
              prop: 'lockDimension',
              overHidden: true
            },
            {
              label: '锁定原因',
              prop: 'lockReason',
              overHidden: true
            }
          ]
        },
        data: []
      },
      loading: true,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      form: {},
      query: {},
      selectionList: [],
      modalName: '',
      tableOption: {},
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  watch: {
    'form.lockDimension': {
      handler(value) {
        if (value == 'ROUTE') {
          // 获取工序列表
          if (this.form.workOrderId) {
            this.getProcessList(this.form.workOrderId);
          }
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.processLock_add, false)
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    handleAdd() {
      this.option.group[1].column[1].dicData = [];
      this.$refs.crud.rowAdd();
    },
    handleView(row, index) {
      this.$refs.crud.rowView(row, index);
    },
    unlockDelete(row, index) {
      this.unlockData.data.splice(index, 1);
    },
    searchChange(params, done) {
      if (params.lockedTimes && params.lockedTimes.length > 0) {
        params.startTime = params.lockedTimes[0];
        params.endTime = params.lockedTimes[1];
        delete params.lockedTimes;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          data.records.forEach((item) => {
            if (item.lockDimension == 'WORKORDER') {
              item.lockDimensionStr = '工单';
            } else {
              item.lockDimensionStr = '工序' + '(' + item.lockDimensionDetail + ')';
            }
          });
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    openWorkOrderModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'workOrderModal';
      this.tableOption = {
        modalTitle: '选择工单信息（双击进行选择）',
        url: '/api/mes-product/work-order/page?workOrderStatus=1,2,3',
        isPage: true,
        index: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '产品编码',
            prop: 'productPartNo'
          },
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '产品型号',
            prop: 'productPartModel'
          },
          {
            label: '生产批次',
            prop: 'lotNo',
            search: true
          }
        ]
      };
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderModal':
          this.form.workOrderId = this._get(rowData, 'id', '');
          this.form.workOrderNo = this._get(rowData, 'workOrderNo', '');
          this.form.productPartId = this._get(rowData, 'productPartId', '');
          this.form.productPartNo = this._get(rowData, 'productPartNo', '');
          this.form.productPartName = this._get(rowData, 'productPartName', '');
          this.form.productPartModel = this._get(rowData, 'productPartModel', '');
          this.form.lotNo = this._get(rowData, 'lotNo', '');
          this.form.lockDimensionDetail = '';
          if (this.form.lockDimension == 'ROUTE') {
            this.getProcessList(this.form.workOrderId);
          }
          break;
        default:
          break;
      }
    },
    getProcessList(workOrderId) {
      this.option.group[1].column[1].dicData = [];
      getRoutesByWo(workOrderId)
        .then((res) => {
          let data = res.data.data;
          this.option.group[1].column[1].dicData = data.map((d) => {
            return {
              label: d.routeName,
              value: d.routeName
            };
          });
        })
        .catch((error) => {});
    },
    rowSave(row, done, loading) {
      let params = {
        workOrderId: row.workOrderId,
        workOrderNo: row.workOrderNo,
        productPartId: row.productPartId,
        productPartNo: row.productPartNo,
        productPartName: row.productPartName,
        productPartModel: row.productPartModel,
        lockDimension: row.lockDimension,
        lockDimensionDetail: row.lockDimension == 'WORKORDER' ? 'WORKORDER' : row.lockDimensionDetail,
        lockReason: row.lockReason
      };
      console.log(params, 'params');
      partLock(params).then(
        (res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    handleBatchUnLock() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.unLockType = 'batch';
      this.unlockDialog.show = true;
      this.unlockDialog.form.unlockReason = '';
      let batchData = structuredClone(this.selectionList);
      batchData.forEach((item) => {
        if (item.lockDimension == 'WORKORDER') {
          item.lockDimension = '工单';
        } else {
          item.lockDimension = '工序' + '(' + item.lockDimensionDetail + ')';
        }
      });
      this.unlockData.data = batchData;
    },
    openUnLockDialog(row, index) {
      this.unLockType = 'single';
      this.unlockDialog.show = true;
      this.unlockDialog.form = structuredClone(row);
      this.unlockDialog.form.unlockReason = '';
      console.log(this.unlockDialog.form, 'unlockDialog.form');
    },
    handleunLockSubmit(form, done) {
      if (this.unLockType === 'single') {
        unLock({
          lockRouteIdList: [this.unlockDialog.form.id],
          unlockReason: form.unlockReason
        })
          .then((res) => {
            this.unlockDialog.show = false;
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: res.data.msg
            });
          })
          .finally(() => done());
      } else {
        if (this.unlockData.data.length === 0) {
          this.$message.warning('锁定信息不能为空，请重新选择');
          done();
          return;
        }
        unLock({
          unlockReason: form.unlockReason,
          lockRouteIdList: this.unlockData.data.map((item) => item.id)
        })
          .then(() => {
            this.unlockDialog.show = false;
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.selectionList = [];
            this.$refs.crud && this.$refs.crud.toggleSelection();
          })
          .catch((err) => {})
          .finally(() => {
            done();
          });
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss">
.avue-dialog {
  .materialLockDialog {
    .el-dialog__body {
      padding-top: 0;
      .brandList {
        .avue-crud__menu {
          display: none;
        }
      }
    }
  }
}
.materialUnlockDialog {
  .el-dialog__body {
    padding-top: 0;
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
